import streamlit as st
import pandas as pd
import plotly.express as px
import numpy as np  # 添加numpy导入

# 页面配置
st.set_page_config(
    page_title="Streamlit Demo",
    page_icon="📊",
    layout="wide"
)

# 标题
st.title("📊 Streamlit数据可视化示例")
st.markdown("---")

# 侧边栏
with st.sidebar:
    st.header("🔧 配置面板")
    
    # 数据生成配置
    num_points = st.slider("数据点数量", 10, 100, 50)
    chart_type = st.selectbox(
        "图表类型",
        ["折线图", "柱状图", "散点图", "饼图"]
    )

# 生成示例数据
df = pd.DataFrame({
    '日期': pd.date_range('2024-01-01', periods=num_points),
    '数值': np.random.randn(num_points).cumsum(),
    '类别': np.random.choice(['A', 'B', 'C'], num_points)
})

# 主要内容区
col1, col2 = st.columns(2)

with col1:
    st.subheader("📈 数据预览")
    st.dataframe(df, use_container_width=True)

with col2:
    st.subheader("📊 可视化展示")
    
    if chart_type == "折线图":
        fig = px.line(df, x='日期', y='数值', color='类别')
    elif chart_type == "柱状图":
        fig = px.bar(df, x='日期', y='数值', color='类别')
    elif chart_type == "散点图":
        fig = px.scatter(df, x='日期', y='数值', color='类别')
    else:  # 饼图
        fig = px.pie(df, values='数值', names='类别')
    
    st.plotly_chart(fig, use_container_width=True)

# 统计信息
st.markdown("---")
st.subheader("📊 统计信息")
col1, col2, col3 = st.columns(3)

with col1:
    st.metric("数据点数量", num_points)
with col2:
    st.metric("平均值", f"{df['数值'].mean():.2f}")
with col3:
    st.metric("标准差", f"{df['数值'].std():.2f}")

# 交互式数据筛选
st.markdown("---")
st.subheader("🔍 数据筛选")
selected_categories = st.multiselect(
    "选择类别",
    df['类别'].unique(),
    default=df['类别'].unique()
)

filtered_df = df[df['类别'].isin(selected_categories)]
st.dataframe(filtered_df, use_container_width=True)

# 下载按钮
st.markdown("---")
st.download_button(
    "📥 下载数据",
    filtered_df.to_csv(index=False).encode('utf-8'),
    "data.csv",
    "text/csv",
    key='download-csv'
)